package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.NearUserVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.TodayBestVo;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private UserLocationApi userLocationApi;

    /**
     * 今日佳人
     */
    public ResponseEntity<Object> queryTodayBest() {
        // 1.获取当前登录用户id
        Long userId = UserHolder.getUserId();

        // 2.调用服务提供者api查询今日佳人
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);

        // 如果没有推荐用户，设置默认数据
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setRecommendUserId(20L);
            recommendUser.setScore(90D);
        }

        // 3.封装返回数据
        TodayBestVo vo = new TodayBestVo();

        // 3.1 封装推荐用户的详情信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            // 单独封装标签
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                String[] tags = userInfo.getTags().split(",");
                vo.setTags(tags);
            }

        }
        // 3.2 封装缘分值
        vo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(vo);
    }

    /**
     * 接口名称：推荐朋友
     */
    public ResponseEntity<Object> queryRecommendation(Integer page, Integer pagesize) {
        // 1.获取当前登录用户id
        Long userId = UserHolder.getUserId();

        // 2.调用服务提供者api分页查询推荐用户列表
        PageResult pageResult = recommendUserApi.queryRecommendation(page, pagesize, userId);

        // 获取当前页的数据
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();

        // 如果没有推荐数据，设置默认数据
        if (recommendUserList == null) {
            recommendUserList = new ArrayList<>();
            for (long i = 5; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setRecommendUserId(i);
                recommendUser.setScore(80D);
                recommendUserList.add(recommendUser);
            }
        }

        // 3.封装返回结果
        List<TodayBestVo> voList = new ArrayList<>();

        List<Long> idList = new ArrayList<>(); // 包装id集合
        for (RecommendUser recommendUser : recommendUserList) {
            idList.add(recommendUser.getRecommendUserId());
        }

        // 调用服务提供者Api
//        List<UserInfo> userInfoList = userInfoApi.findByIds(idList);
//        Map<Long, UserInfo> map = new HashMap<>();
//
//        for (UserInfo userInfo : userInfoList) {
//            map.put(userInfo.getId(), userInfo);
//        }

        for (RecommendUser recommendUser : recommendUserList) {
            TodayBestVo vo = new TodayBestVo();

//            for (UserInfo userInfo : userInfoList) {
//                if(recommendUser.getRecommendUserId() == userInfo.getId()){
//
//                }
//            }
//            UserInfo userInfo1 = map.get(recommendUser.getRecommendUserId());


            // 3.1 封装推荐用户的详情信息
            UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
            if (userInfo != null) {
                BeanUtils.copyProperties(userInfo, vo);
                // 单独封装标签
                if (!StringUtils.isEmpty(userInfo.getTags())) {
                    String[] tags = userInfo.getTags().split(",");
                    vo.setTags(tags);
                }

            }
            // 3.2 封装缘分值
            vo.setFateValue(recommendUser.getScore().longValue());

            // 3.3 添加vo到集合
            voList.add(vo);
        }

        // 4.重新设置items的值
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 佳人信息
     */
    public ResponseEntity<Object> queryPersonalInfo(Long id) {
        // 1.查询佳人用户详情
        UserInfo userInfo = userInfoApi.findById(id);

        // 2.封装返回结果
        TodayBestVo vo = new TodayBestVo();
        // 2.1 封装用户详情
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        // 2.2 封装佳人的缘分值
        // 调用服务提供者查询缘分值
        long score = recommendUserApi.queryScore(UserHolder.getUserId(), id);
        vo.setFateValue(score);

        return ResponseEntity.ok(vo);
    }

    /**
     * 查询陌生人问题
     */
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        // 查询某用户的陌生人问题
        Question question = questionApi.findByUserId(userId);

        String content = question != null ? question.getTxt() : "你喜欢我吗？";

        return ResponseEntity.ok(content);
    }

    /**
     * 回复陌生人问题
     */
    public ResponseEntity<Object> replyQuestion(Integer userId, String reply) {
        // 1.创建消息内容，并封装为json字符串
        Map<String, Object> msg = new HashMap<>();

        msg.put("userId", UserHolder.getUserId());  // 发送者id
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());   // 获取当前用户详情
        msg.put("nickname", userInfo.getNickname()); // 发送者的昵称
        Question question = questionApi.findByUserId(userId.longValue());  // 查询目标用户的陌生人问题
        msg.put("strangerQuestion", question != null ? question.getTxt() : "你喜欢我吗？");
        msg.put("reply", reply);

        // 2.发送到环信平台，参数1-目标用户id，参数2-消息json字符串
        huanXinTemplate.sendMsg(userId.toString(), JSON.toJSONString(msg));

        return ResponseEntity.ok(null);
    }

    /**
     * 接口名称：搜附近
     */
    public ResponseEntity<Object> searchNear(String gender, Long distance) {
        // 1.获取当前登录用户的id
        Long userId = UserHolder.getUserId();

        // 2.调用服务提供者查询附近的人用户id集合
        List<Long> userIdList = userLocationApi.searchNear(userId, distance);

        // 3.封装返回结果
        List<NearUserVo> voList = new ArrayList<>();

        if (userIdList != null && userIdList.size() > 0) {
            // 筛选性别、排除自己
            List<UserInfo> userInfoList = userInfoApi.findByIdList(userIdList, gender, userId);
            if (userInfoList != null && userInfoList.size() > 0) {
                for (UserInfo userInfo : userInfoList) {
                    // 3.1 创建vo
                    NearUserVo vo = new NearUserVo();
                    vo.setUserId(userInfo.getId());
                    vo.setAvatar(userInfo.getAvatar());
                    vo.setNickname(userInfo.getNickname());

                    voList.add(vo);
                }
            }
        }
        return ResponseEntity.ok(voList);
    }
}
